package com.yiyahui.project.erp.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import com.yiyahui.common.utils.DateUtils;
import com.yiyahui.common.utils.ServletUtils;
import com.yiyahui.common.utils.StringUtils;
import com.yiyahui.common.utils.spring.SpringUtils;
import com.yiyahui.framework.redis.RedisCache;
import com.yiyahui.framework.security.LoginUser;
import com.yiyahui.framework.security.service.TokenService;
import com.yiyahui.project.erp.domain.YiyaClinicPerson;
import com.yiyahui.project.erp.domain.YiyaDailyBrowserInfo;
import com.yiyahui.project.erp.domain.YiyaMarketReservation;
import com.yiyahui.project.erp.domain.YiyaOperationLog;
import com.yiyahui.project.erp.mapper.YiyaOperationLogMapper;
import com.yiyahui.project.erp.service.IYiyaClinicPersonService;
import com.yiyahui.project.erp.service.IYiyaMarketReservationService;
import com.yiyahui.project.erp.service.IYiyaOperationLogService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 操作日志Service接口
 * 
 * @author yiyahui
 * @date 2020-05-23
 */
@Service
public class YiyaOperationLogServiceImpl implements IYiyaOperationLogService {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IYiyaClinicPersonService yiyaClinicPersonService;

    @Autowired
    private IYiyaMarketReservationService yiyaMarketReservationService;

    @Autowired
    private YiyaOperationLogMapper yiyaOperationLogMapper;

    /**
     * 获取每日浏览日志
     * 
     * @param date 日期
     * @return 每日浏览list
     */
    @Override
    public List<YiyaDailyBrowserInfo> getDailyBrowserList(int type, Date date, int start, int end) {
        List<YiyaDailyBrowserInfo> list = new ArrayList<YiyaDailyBrowserInfo>();
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        String key = "browserlog:";
        key += ((type == 0) ? "MARKET" : "MEMBER") + DateUtils.parseDateToStr("yyyyMMdd", date)
                + loginUser.getUsername() + ":";
        String sortkey = key + "time";
        Set<Long> st = redisCache.redisTemplate.boundZSetOps(sortkey).range(start, end);
        for (Long _key : st) {
            Map<String, Object> map = redisCache.getCacheMap(key + _key);
            YiyaDailyBrowserInfo info = JSON.parseObject(JSON.toJSONString(map), YiyaDailyBrowserInfo.class);
            list.add(info);
        }
        return list;
    }

    /**
     * 插入每日浏览日志
     * 
     * @param type   类型
     * @param userid 用户id（根据类型区分）
     * @return 插入结果
     */
    @Override
    public int insertDailyBrowserLog(int type, Long userid) {
        // 获取当前的用户
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        Date date = DateUtils.getNowDate();
        String key = "browserlog:";
        key += ((type == 0) ? "MARKET" : "MEMBER") + DateUtils.dateTime() + loginUser.getUsername() + ":";
        String timekey = key + "time";
        key += userid;
        Map<String, Object> values = redisCache.getCacheMap(key);
        if (values.size() != 0) {// 仅修改时间
            values.put("datetime", date);
            redisCache.setCacheMap(key, values);
            redisCache.redisTemplate.boundZSetOps(timekey).add(userid, date.getTime());
        } else {// 新增记录
            YiyaDailyBrowserInfo info = new YiyaDailyBrowserInfo();
            if (type == 1) {
                YiyaClinicPerson person = yiyaClinicPersonService.selectYiyaClinicPersonById(userid);
                info.setUserid(userid);
                info.setAge(person.getAge());
                info.setName(person.getName());
                info.setSex(person.getSex());
                info.setPhone1(person.getPhoneNumber());
                info.setPhone2(person.getPhoneNumber2());
                info.setOwnership1(person.getPhoneOwnership());
            } else if (type == 0) {
                YiyaMarketReservation person = yiyaMarketReservationService.selectYiyaMarketReservationById(userid);
                info.setUserid(userid);
                info.setAge(person.getAge());
                info.setName(person.getName());
                info.setSex(person.getSex());
                info.setPhone1(person.getPhoneNumber());
                info.setPhone2(person.getPhoneNumber2());
                info.setOwnership1(person.getPhoneOwnership());
                info.setOwnership2(person.getPhoneOwnership2());
            }

            info.setDatetime(date);// 设置浏览时间
            Map<String, Object> redismap = JSON.parseObject(JSON.toJSONString(info), Map.class);
            redismap.put("key", key);// 将key也置入，方便删除
            redisCache.setCacheMap(key, redismap);
            redisCache.redisTemplate.boundZSetOps(timekey).add(userid, date.getTime());
        }

        return 1;
    }

    /**
     * 删除某条每日浏览日志
     * 
     * @param id数组
     * @return 删除结果
     */
    @Override
    public int deleteDailyBrowserLog(String[] keys) {
        for (String key : keys) {
            redisCache.deleteObject(key);
            String[] tmp = key.split(":");
            Long userid = Long.valueOf(tmp[tmp.length-1]);
            tmp[tmp.length-1] = "time";
            key = StringUtils.join(tmp,":");
            redisCache.redisTemplate.boundZSetOps(key).remove(userid);
        }
        return 1;
    }

    /*******************************
     * 普通操作日志接口
     *****************************************/

    /**
     * 查询操作日志
     * 
     * @param id 操作日志ID
     * @return 操作日志
     */
    @Override
    public YiyaOperationLog selectYiyaOperationLogById(Long id) {
        return yiyaOperationLogMapper.selectYiyaOperationLogById(id);
    }

    /**
     * 查询操作日志列表
     * 
     * @param yiyaOperationLog 操作日志
     * @return 操作日志
     */
    @Override
    public List<YiyaOperationLog> selectYiyaOperationLogList(YiyaOperationLog yiyaOperationLog) {
        return yiyaOperationLogMapper.selectYiyaOperationLogList(yiyaOperationLog);
    }

    /**
     * 新增操作日志
     * 
     * @param yiyaOperationLog 操作日志
     * @return 结果
     */
    @Override
    public int insertYiyaOperationLog(YiyaOperationLog yiyaOperationLog) {
        return yiyaOperationLogMapper.insertYiyaOperationLog(yiyaOperationLog);
    }

    /**
     * 修改操作日志
     * 
     * @param yiyaOperationLog 操作日志
     * @return 结果
     */
    @Override
    public int updateYiyaOperationLog(YiyaOperationLog yiyaOperationLog) {
        return yiyaOperationLogMapper.updateYiyaOperationLog(yiyaOperationLog);
    }

    /**
     * 批量删除操作日志
     * 
     * @param ids 需要删除的操作日志ID
     * @return 结果
     */
    @Override
    public int deleteYiyaOperationLogByIds(Long[] ids) {
        return yiyaOperationLogMapper.deleteYiyaOperationLogByIds(ids);
    }

    /**
     * 删除操作日志信息
     * 
     * @param id 操作日志ID
     * @return 结果
     */
    @Override
    public int deleteYiyaOperationLogById(Long id) {
        return yiyaOperationLogMapper.deleteYiyaOperationLogById(id);
    }

    @Override
    public int insertYellowPageNoLog(Long id) {
        // TODO Auto-generated method stub
        return 0;
    }
}